package initialize

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"gopkg.in/yaml.v2"
	"log"
	book_rpc "month_zg5/book_srv/proto"
	"month_zg5/client/common/global"
	"month_zg5/client/routers"
	consule "month_zg5/client/vender/consul"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func init() {
	InitViper()
	InitNacos()
	InitRouter()
	//InitMysql()
}
func InitViper() {
	path := "./etc/dev.yaml"
	viper.SetConfigFile(path)
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.Unmarshal(&global.NacosConfig)
}
func InitNacos() {
	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.NacosConfig.NacosName, // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogLevel:            "debug",
	}

	// 至少一个ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: global.NacosConfig.Host,
			Port:   uint64(global.NacosConfig.Port),
		},
	}

	// 创建动态配置客户端的另一种方式 (推荐)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(err)
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosConfig.DataId,
		Group:  global.NacosConfig.Group,
	})
	if err != nil {
		panic(err)
	}
	yaml.Unmarshal([]byte(content), &global.ClientConfig)
	log.Println(global.ClientConfig.AesConf.Key, ";;;;")
}
func InitRouter() {
	global.Router = gin.New()
	Group := global.Router.Group("v1")
	routers.UserRouter(Group)
	routers.BookRouter(Group)
}
func InitWebServer() {
	server := &http.Server{
		Addr:    fmt.Sprintf(":%d", global.ClientConfig.ApiConf.Port),
		Handler: global.Router,
	}
	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			panic(err)
		}
	}()
	consulClient := InitConsul()
	SigChan := make(chan os.Signal, 1)
	signal.Notify(SigChan, syscall.SIGTERM, syscall.SIGINT)
	<-SigChan
	err := consulClient.Deregister(global.ClientConfig.ConsulConf.Id)
	if err != nil {
		panic(err)
	}
}
func InitConsul() consule.RegistryClient {
	var (
		err error
	)
	global.ConsulClient, err = api.NewClient(api.DefaultConfig())
	if err != nil {
		panic(err)
	}
	//服务发现
	consulClient := consule.NewRegistryClient(global.ClientConfig.ApiConf.Host, global.ClientConfig.ApiConf.Port)
	name, i, err := consulClient.AgentHealthServiceByName(global.ClientConfig.ConsulConf.BookConsulName)
	if err != nil {
		panic(err)
	}
	if name != "passing" {
		panic("is not health service")
	}
	//拨号
	conn, err := grpc.Dial(fmt.Sprintf("%s:%d", i[0].Service.Address, i[0].Service.Port), grpc.WithBlock(), grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic(err)
	}
	global.BookClient = book_rpc.NewBookClient(conn)
	//注册
	global.ClientConfig.ConsulConf.Id = uuid.NewString()
	err = consulClient.RegisterConsul(global.ClientConfig.ConsulConf.Id, global.ClientConfig.ConsulConf.Name, global.ClientConfig.ConsulConf.Tags)
	if err != nil {
		log.Println("注册失败")
		return nil
	}
	return consulClient
}

//func InitMysql() {
//	var err error
//	dsn := "root:root@tcp(127.0.0.1:3306)/blog?charset=utf8mb4&parseTime=True&loc=Local"
//	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
//		NamingStrategy: schema.NamingStrategy{
//			SingularTable: true,
//			TablePrefix:   "book_",
//		},
//	})
//	if err != nil {
//		panic(err)
//	}
//}
